package com.czg.jsonschema2lombokpojo;

import java.io.IOException;
import java.net.URI;
import java.net.URL;

import com.czg.jsonschema2lombokpojo.rules.RuleFactory;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;

/**
 * 从JSONschema生成Java类型。可以接受一个工厂，该工厂将用于为该映射器创建类型生成规则。
 */
public class SchemaMapper {
    private static final JsonNodeFactory NODE_FACTORY = JsonNodeFactory.instance;

    private final RuleFactory ruleFactory;
    private final SchemaGenerator schemaGenerator;

    /**
     * 使用给定的{@link RuleFactory}创建一个schema映射器。
     *
     * @param ruleFactory     映射器用来创建Java类型生成规则的工厂。
     * @param schemaGenerator 如果配置指定输入文档为纯json（而不是jsonschema），该映射器将使用的生成器
     */
    public SchemaMapper(RuleFactory ruleFactory, SchemaGenerator schemaGenerator) {
        this.ruleFactory = ruleFactory;
        this.schemaGenerator = schemaGenerator;
    }

    /**
     * 用默认的{@link RuleFactory}实现创建一个schema映射器。
     * <p>
     * 参见 RuleFactory
     */
    public SchemaMapper() {
        this(new RuleFactory(), new SchemaGenerator());
    }

    /**
     * 读取schema并将生成的类型添加到给定的代码模型。
     *
     * @param codeModel   应该用于生成新类型的Java代码生成上下文
     * @param className   该schema所表示的父类的名称
     * @param packageName 生成的类型应该使用的目标包
     * @param schemaUrl   要用作输入的schema的位置
     * @return 从给定文件生成的最上面的类型
     */
    public JType generate(JCodeModel codeModel, String className, String packageName, URL schemaUrl) {

        JPackage jpackage = codeModel._package(packageName);

        ObjectNode schemaNode = readSchema(schemaUrl);
        Schema currentSchema = new Schema(null, schemaNode, null);
        return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, currentSchema);

    }

    private ObjectNode readSchema(URL schemaUrl) {

        switch (ruleFactory.getGenerationConfig().getSourceType()) {
            case JSONSCHEMA:
            case YAMLSCHEMA:
                ObjectNode schemaNode = NODE_FACTORY.objectNode();
                schemaNode.put("$ref", schemaUrl.toString());
                return schemaNode;
            case JSON:
            case YAML:
                return schemaGenerator.schemaFromExample(schemaUrl);
            default:
                throw new IllegalArgumentException("无法识别的源类型: " + ruleFactory.getGenerationConfig().getSourceType());
        }

    }

    public JType generate(JCodeModel codeModel, String className, String packageName, String json,
                          URI schemaLocation) throws IOException {

        JPackage jpackage = codeModel._package(packageName);

        JsonNode schemaNode = objectMapper().readTree(json);

        return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage,
                new Schema(schemaLocation, schemaNode, null));
    }

    public JType generate(JCodeModel codeModel, String className, String packageName, String json) throws IOException {

        JPackage jpackage = codeModel._package(packageName);

        JsonNode schemaNode = null;
        if (ruleFactory.getGenerationConfig().getSourceType() == SourceType.JSON
                || ruleFactory.getGenerationConfig().getSourceType() == SourceType.YAML) {
            JsonNode jsonNode = objectMapper().readTree(json);
            schemaNode = schemaGenerator.schemaFromExample(jsonNode);
        } else {
            schemaNode = objectMapper().readTree(json);
        }

        return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(null, schemaNode, null));
    }

    private ObjectMapper objectMapper() {
        return new ObjectMapper()
                .enable(JsonParser.Feature.ALLOW_COMMENTS)
                .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    }

    public RuleFactory getRuleFactory() {
        return ruleFactory;
    }

}
